package com.example.tasks;

import com.example.jobtask.service.HotPlugContextService;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;

/**
 * 示例热插拔任务：数据库操作任务
 * 演示如何在热插拔任务中使用数据库连接
 */
public class DatabaseTask {
    
    /**
     * 查询用户数量
     */
    public String queryUserCount() {
        try {
            HotPlugContextService contextService = HotPlugContextService.getInstance();
            
            // 方法1：使用封装的查询方法
            Map<String, Object> result = contextService.queryForMap(
                "SELECT COUNT(*) as user_count FROM job_sys_user WHERE status = ?", 1
            );
            
            String message = String.format("当前活跃用户数量: %s, 查询时间: %s", 
                result.get("user_count"),
                LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
            );
            
            System.out.println("[DatabaseTask] " + message);
            return message;
            
        } catch (Exception e) {
            String errorMsg = "查询用户数量失败: " + e.getMessage();
            System.err.println("[DatabaseTask] " + errorMsg);
            return errorMsg;
        }
    }
    
    /**
     * 查询最近登录的用户
     */
    public String queryRecentUsers() {
        try {
            HotPlugContextService contextService = HotPlugContextService.getInstance();
            
            // 方法2：直接使用数据库连接
            StringBuilder result = new StringBuilder();
            result.append("最近登录的用户:\n");
            
            try (Connection conn = contextService.getConnection();
                 PreparedStatement ps = conn.prepareStatement(
                     "SELECT username, real_name, last_login_time FROM job_sys_user " +
                     "WHERE last_login_time IS NOT NULL ORDER BY last_login_time DESC LIMIT 5")) {
                
                try (ResultSet rs = ps.executeQuery()) {
                    int count = 0;
                    while (rs.next()) {
                        count++;
                        result.append(String.format("%d. 用户: %s (%s), 最后登录: %s\n",
                            count,
                            rs.getString("username"),
                            rs.getString("real_name"),
                            rs.getTimestamp("last_login_time")
                        ));
                    }
                    
                    if (count == 0) {
                        result.append("暂无登录记录\n");
                    }
                }
            }
            
            result.append("查询时间: ").append(
                LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
            );
            
            String message = result.toString();
            System.out.println("[DatabaseTask] " + message);
            return message;
            
        } catch (Exception e) {
            String errorMsg = "查询最近用户失败: " + e.getMessage();
            System.err.println("[DatabaseTask] " + errorMsg);
            return errorMsg;
        }
    }
    
    /**
     * 更新用户最后活跃时间
     */
    public String updateUserActivity(String username) {
        try {
            HotPlugContextService contextService = HotPlugContextService.getInstance();
            
            // 使用封装的更新方法
            int affected = contextService.executeUpdate(
                "UPDATE job_sys_user SET update_time = NOW() WHERE username = ?", 
                username
            );
            
            String message = String.format("更新用户 %s 活跃时间，影响行数: %d, 更新时间: %s",
                username, affected,
                LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
            );
            
            System.out.println("[DatabaseTask] " + message);
            return message;
            
        } catch (Exception e) {
            String errorMsg = "更新用户活跃时间失败: " + e.getMessage();
            System.err.println("[DatabaseTask] " + errorMsg);
            return errorMsg;
        }
    }
    
    /**
     * 获取系统统计信息
     */
    public String getSystemStats() {
        try {
            HotPlugContextService contextService = HotPlugContextService.getInstance();
            
            StringBuilder stats = new StringBuilder();
            stats.append("=== 系统统计信息 ===\n");
            
            // 用户统计
            Map<String, Object> userStats = contextService.queryForMap(
                "SELECT COUNT(*) as total_users, " +
                "SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) as active_users, " +
                "SUM(CASE WHEN role = 'ADMIN' THEN 1 ELSE 0 END) as admin_users " +
                "FROM job_sys_user"
            );
            
            stats.append(String.format("用户总数: %s\n", userStats.get("total_users")));
            stats.append(String.format("活跃用户: %s\n", userStats.get("active_users")));
            stats.append(String.format("管理员数: %s\n", userStats.get("admin_users")));
            
            // 任务统计
            Map<String, Object> taskStats = contextService.queryForMap(
                "SELECT COUNT(*) as total_tasks, " +
                "SUM(CASE WHEN status = 'ACTIVE' THEN 1 ELSE 0 END) as active_tasks " +
                "FROM job_tasks"
            );
            
            stats.append(String.format("任务总数: %s\n", taskStats.get("total_tasks")));
            stats.append(String.format("活跃任务: %s\n", taskStats.get("active_tasks")));
            
            stats.append("统计时间: ").append(
                LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
            );
            
            String message = stats.toString();
            System.out.println("[DatabaseTask] " + message);
            return message;
            
        } catch (Exception e) {
            String errorMsg = "获取系统统计失败: " + e.getMessage();
            System.err.println("[DatabaseTask] " + errorMsg);
            return errorMsg;
        }
    }
}